<template>
    <div class="app-container">
        <el-card>
            <el-page-header @back="goBack">
                <template #content>
                    <div class="flex items-center">
                        <div v-if="!route.query?.id">新增补版单</div>
                        <div v-else>
                            <span class="text-sm mr-2" style="color: var(--el-text-color-regular)">
                                补版单编码:
                            </span>
                            <el-tag>{{ form.code }}</el-tag>
                        </div>
                    </div>
                </template>
                <template #extra>
                    <div class="flex items-center" v-if="!route.query.info">
                        <el-button type="primary" @click="submitForm">保 存</el-button>
                    </div>
                </template>
            </el-page-header>
        </el-card>
        <el-card style="margin-top: 10px">
            <el-collapse v-model="activeNames">
                <el-collapse-item disabled title="基本信息" name="1">
                    <template #title>
                        <el-icon style="color: #4479f6">
                            <Position />
                        </el-icon>
                        <span class="title">基本信息</span>
                    </template>
                    <div>
                        <el-form
                            :model="form"
                            :rules="rules"
                            :disabled="flag"
                            ref="userRef"
                            label-width="130px"
                        >
                            <el-row :gutter="20">
                                <el-col :span="8">
                                    <el-form-item label="补版日期" prop="replenishDate">
                                        <el-date-picker
                                            style="width: 100%"
                                            clearable
                                            v-model="form.replenishDate"
                                            value-format="YYYY-MM-DD"
                                            type="date"
                                            placeholder="请选择日期"
                                        />
                                    </el-form-item>
                                </el-col>
                                <!-- <el-col :span="8">
                                    <el-form-item label="制版人" prop="applyName">
                                        <el-input v-model="form.applyName" readonly placeholder="" />
                                    </el-form-item>
                                </el-col> -->

                                <!-- <el-col :span="8">
                                    <el-form-item label="创建人" prop="createBy">
                                        <el-input v-model="form.createBy" readonly placeholder="" />
                                    </el-form-item>
                                </el-col> -->
                                <el-col :span="8">
                                    <el-form-item label="申请人" prop="applyName">
                                        <el-input
                                            v-model="form.applyName"
                                            readonly
                                            placeholder=""
                                        />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="申请机台/部门" prop="applyMachine">
                                        <el-select
                                            v-model="form.applyMachine"
                                            clearable
                                            filterable
                                            style="width: 100%"
                                        >
                                            <el-option
                                                v-for="item in Myoptions"
                                                :key="item.pid"
                                                :label="item.machineName"
                                                :value="item.machineName"
                                            />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="8">
                                    <el-form-item label="申请日期" prop="applyDate">
                                        <el-date-picker
                                            style="width: 100%"
                                            readonly
                                            v-model="form.applyDate"
                                            value-format="YYYY-MM-DD"
                                            type="date"
                                            placeholder="请选择时间"
                                        />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="24">
                                    <el-form-item label="备注">
                                        <el-input
                                            v-model="form.remark"
                                            type="textarea"
                                            placeholder="请输入内容"
                                        ></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </div>
                </el-collapse-item>
                <el-collapse-item disabled title="补版明细" name="2">
                    <template #title>
                        <el-icon style="color: #4479f6">
                            <Position />
                        </el-icon>
                        <span class="title">补版明细</span>
                    </template>
                    <el-button
                        v-if="!flag"
                        style="margin-bottom: 10px"
                        type="primary"
                        size="small"
                        @click="handleAddStorage"
                    >
                        选择生产单
                    </el-button>
                    <el-table v-loading="loading" class="table-form" :data="mesReplenishDetailList">
                        <el-table-column
                            label="序号"
                            width="60"
                            type="index"
                            align="center"
                        ></el-table-column>
                        <el-table-column
                            label="制版序列号"
                            min-width="120"
                            prop="printProduceNo"
                            align="center"
                        ></el-table-column>
                        <el-table-column
                            label="生产单编码"
                            align="center"
                            width="120"
                            prop="produceNo"
                        ></el-table-column>

                        <el-table-column
                            label="印刷序列号"
                            min-width="120"
                            prop="printProduceNo"
                            align="center"
                        ></el-table-column>
                        <el-table-column label="品种" prop="breed" min-width="160" align="center">
                            <!-- <template #default="scope">
                              <dict-tag
                                  :options="ems_order_breed_type"
                                  :value="scope.row.breed"
                              />
                          </template> -->
                        </el-table-column>
                        <el-table-column
                            label="组成"
                            min-width="160"
                            prop="composition"
                            align="center"
                        ></el-table-column>
                        <el-table-column
                            label="印张"
                            width="120"
                            prop="sheet"
                            align="center"
                        ></el-table-column>
                        <el-table-column
                            label="印数"
                            width="120"
                            prop="printAmount"
                            align="center"
                        ></el-table-column>
                        <el-table-column label="印色" width="120" prop="printColour" align="center">
                            <template #default="scope">
                                <dict-tag
                                    :options="ems_order_print_color"
                                    :value="scope.row.printColour"
                                />
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="版材数量"
                            width="120"
                            prop="sheetAmount"
                            align="center"
                        ></el-table-column>
                        <el-table-column
                            label="版材尺寸"
                            prop="sheetSize"
                            width="120"
                            align="center"
                        >
                            <template #default="scope">
                                <dict-tag
                                    :options="ems_machine_info_size"
                                    :value="scope.row.sheetSize"
                                />
                            </template>
                        </el-table-column>

<!--                        <el-table-column-->
<!--                            label="制版数量"-->
<!--                            width="120"-->
<!--                            align="center"-->
<!--                            prop="replenishNumber"-->
<!--                        >-->
<!--                            <template #default="scope">-->
<!--                                <el-form-item>-->
<!--                                    <el-input-->
<!--                                        v-model="scope.row.replenishNumber"-->
<!--                                        placeholder="请输入"-->
<!--                                    ></el-input>-->
<!--                                </el-form-item>-->
<!--                            </template>-->
<!--                        </el-table-column>-->


                      <el-table-column
                          label="补版数量"
                          width="120"
                          align="center"
                          prop="replenishNumber"
                      >
                        <template #default="scope">
                          <el-form-item>
                            <el-input  v-if="!route.query.info"
                                       :max="scope.row.sheetAmount"
                                       @mousewheel.prevent
                                       @blur="changePieceLing(scope.row, scope.$index)"
                                       v-model="scope.row.replenishNumber"
                                       type="number"
                                       placeholder="请输入"
                            ></el-input>
                            <el-input  v-if="route.query.info"  disabled
                                       v-model="scope.row.replenishNumber"
                                       placeholder="请输入"
                            ></el-input>
                          </el-form-item>
                        </template>
                      </el-table-column>



                        <el-table-column label="烤版" width="120" prop="kaoban" align="center">
                            <template #default="scope">
                                {{
                                    scope.row?.kaoban == 1
                                        ? '是'
                                        : scope.row?.kaoban == 2
                                        ? '否'
                                        : ''
                                }}
                            </template>
                        </el-table-column>
                        <el-table-column
                          label="做版人"
                          width="120"
                          align="center"
                          prop="makeBy"
                      ></el-table-column>
                        <el-table-column
                            label="备注"
                            width="120"
                            align="center"
                            prop="remark"
                            :show-overflow-tooltip="true"
                        >
                            <template #default="scope">
                                <span v-if="flag">{{ scope.row.remark }}</span>
                                <el-form-item v-else>
                                    <el-input
                                        v-model="scope.row.remark"
                                        placeholder="请输入"
                                    ></el-input>
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="操作"
                            v-if="!flag"
                            align="center"
                            fixed="right"
                            class-name="small-padding fixed-width"
                        >
                            <template #default="scope">
                                <el-tooltip content="删除" placement="top">
                                    <el-button
                                        link
                                        type="primary"
                                        icon="Delete"
                                        @click="handleDelete(scope.row)"
                                    ></el-button>
                                </el-tooltip>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-collapse-item>
            </el-collapse>
        </el-card>
        <!-- 领用库单明细 -->
        <orderList
            :visible="orderListOpen"
            @changeUpdate="changeOrderData"
            :orderSelectList="orderSelectList"
            :machineId="selectMachineId"
            @cancel="
                () => {
                    orderListOpen = false
                }
            "
        ></orderList>
        <SearchWorkBench
            :visible="searchVisible"
            @changeUpdate="changeWorkBenchData"
            @cancel="
                () => {
                    searchVisible = false
                }
            "
        ></SearchWorkBench>
    </div>
</template>

<script setup>
import { getList as getDataList } from '@/api/basicInfo/workbench'
import SearchWorkBench from '@/components/SearchWorkBench'
import orderList from './orderList.vue'
import {
    editMesreplenish,
    addMesreplenish,
    getByIdMesreplenish,
} from '@/api/production/supplementary.js'
import useTagsViewStore from '@/store/modules/tagsView'
import useUserStore from '@/store/modules/user'
import { ElMessage } from 'element-plus'
import { nextTick } from 'vue'
const tagsViewStore = useTagsViewStore()
const { proxy } = getCurrentInstance()
const {
    ems_machine_info_size,
    ems_order_make_up,
    ems_order_print_color,
    ems_order_breed_type,
    ems_order_make_up_fm,
} = proxy.useDict(
    'ems_order_breed_type',
    'ems_machine_info_size',
    'ems_order_make_up',
    'ems_order_print_color',
    'ems_order_make_up_fm'
)
const route = useRoute()
const router = useRouter()
const orderListOpen = ref(false)
const orderSelectList = ref([])
const activeNames = ['1', '2']
const userRef = ref(null)
const selectMachineId = ref('')
const flag = ref(false)
const searchVisible = ref(false)
const Myoptions = ref([
    { machineName: '旧版房', pid: '999999' },
    { machineName: '印刷机', pid: '888888' },
])
const loading = ref(false)
const userInfo = useUserStore()
const changeMultipleReport = (row, index) => {
  changePieceLing(row, index);
};
const changePieceLing = (row, index) => {
  if (
      row.replenishNumber>row.sheetAmount
  ) {
    return ElMessage({
      message: '补版数量不能大于版材数量',
      type: 'warning',
    })
  }
}
const data = reactive({
    form: {},
    mesReplenishDetailList: [],
    rules: {
        // applyName: [{ required: true, message: '取版人不能为空', trigger: 'change' }],
        replenishDate: [
            { required: true, message: '补版日期不能为空', trigger: ['blur', 'change'] },
        ],
        applyMachine: [
            { required: true, message: '申请机台/部门不能为空', trigger: ['blur', 'change'] },
        ],
    },
})

const { form, rules, mesReplenishDetailList } = toRefs(data)

nextTick(() => {
    form.value.createBy = userInfo.name
    form.value.applyName = userInfo.name
})

if (route.query.id) {
    getByIdMesreplenish(route.query.id).then(res => {
        Object.assign(form.value, { ...res.data })
        mesReplenishDetailList.value = res.data.mesReplenishDetailList
        if (route.query.info) {
            flag.value = true
        }
    })
} else {
    flag.value = false
    form.value = {}
    mesReplenishDetailList.value = []
}
// 打开机台页面
const openDialog = () => {
    searchVisible.value = true
}
// 选中的机台
const changeWorkBenchData = row => {
    form.value.applyMachine = row.applyMachine
    form.value.machineId = row.pid
    selectMachineId.value = row.pid
    searchVisible.value = false
}

const getChoiceList = async () => {
    const res = await getDataList({ pageNum: 1, pageSize: 100 })
    Myoptions.value = [{ machineName: '旧版房', pid: '999999' }, ...res.rows]
}

getChoiceList()
// 获取当前时间
const getCurrentDateTime = () => {
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const hours = String(now.getHours()).padStart(2, '0')
    const minutes = String(now.getMinutes()).padStart(2, '0')
    const seconds = String(now.getSeconds()).padStart(2, '0')
    form.value.applyDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
getCurrentDateTime()

// 新增入库明细
const handleAddStorage = () => {
    orderSelectList.value = mesReplenishDetailList.value
    orderListOpen.value = true
}
// 选中的入库明细
const changeOrderData = row => {
    const codeSet = new Set(mesReplenishDetailList.value.map(data => data.producePrintId))
    row.forEach(item => {
        if (!codeSet.has(item.producePrintId)) {
            mesReplenishDetailList.value.push({ ...item })
            codeSet.add(item.producePrintId)
        }
    })
    orderListOpen.value = false
}

// 删除
const handleDelete = row => {
    proxy.$modal.confirm('是否确认删除该数据？').then(function () {
        mesReplenishDetailList.value = mesReplenishDetailList.value.filter(item =>
            item.producePrintId ? item.producePrintId != row.producePrintId : item.id != row.id
        )
        proxy.$modal.msgSuccess('删除成功')
    })
}
// 确认
const submitForm = () => {
    userRef.value.validate(valid => {
        if (valid) {
            if (route.query.id) {
                editMesreplenish({
                    ...form.value,
                    mesReplenishDetailList: mesReplenishDetailList.value,
                }).then(res => {
                    ElMessage({
                        message: '编辑成功',
                        type: 'success',
                    })
                    goBack()
                })
            } else {
                addMesreplenish({
                    ...form.value,
                    status: 3,//1
                    mesReplenishDetailList: mesReplenishDetailList.value,
                }).then(res => {
                    ElMessage({
                        message: '新增成功',
                        type: 'success',
                    })
                    goBack()
                })
            }
        }
    })
}
//  返回
const goBack = () => {
    tagsViewStore.delView(route)
    router.go(-1)
}
</script>

<style lang="scss" scoped>
.footer {
    text-align: center;
}

:deep(.el-pagination) {
    position: unset;
}

.table-form :deep(.el-form-item) {
    margin-bottom: 0;
}
</style>
